<template>
  <a-modal
    title="新增二级业务"
    :width="700"
    :visible="visible"
    @cancel="handleCancel"
    @ok="handleSubmit"
    :confirmLoading="confirmLoading"
    :destroyOnClose="true"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item v-bind="formItemLayout" label="一级业务" hasFeedback>
          <a-input
            disabled
            v-decorator="['pName', { rules: [{ required: true, message: '一级业务不能为空' }] }]"
            :maxLength="20"
            placeholder="输入一级业务名称"
          />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="二级业务名称" hasFeedback>
          <a-input
            v-decorator="['name', { rules: [{ required: true, message: '二级名称不能为空' }] }]"
            :maxLength="20"
            placeholder="输入二级业务名称"
          />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="二级业务缩写" :extra="subCode" hasFeedback>
          <a-input
            v-decorator="[
              'code',
              {
                rules: [
                  { required: true, message: '二级业务缩写不能为空' },
                  { pattern: new RegExp(/^[a-zA-Z]*$/), message: '只能输入大小写' },
                ],
              },
            ]"
            :maxLength="20"
            placeholder="输入二级业务业务缩写"
            @change="handleInputChange"
          />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="日志保留天数" hasFeedback>
          <a-select v-decorator="['maxLifeDay', { initialValue: '7' }]" placeholder="选择日志保留天数">
            <a-select-option key="7">7天</a-select-option>
            <a-select-option key="14">14天</a-select-option>
            <a-select-option key="20">20天</a-select-option>
            <a-select-option key="30">30天</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="描述" hasFeedback>
          <a-textarea v-decorator="['description', {}]" :rows="4" placeholder="输入描述" />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { sqlFindOne, sqlUpdate } from '@/api/sql'
import { mapGetters } from 'vuex'
export default {
  name: 'CategoryEditSubModal',
  data () {
    return {
      confirmLoading: false,
      visible: false,
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 18 }
        }
      },
      form: this.$form.createForm(this),
      parent: {},
      result: {},
      subCode: null
    }
  },
  created () {},
  computed: {
    userInfo () {
      return this.$store.getters.userInfo
    }
  },
  methods: {
    ...mapGetters(['nickname']),

    /**
     * 初始化
     */
    async init (parent, result) {
      console.log(parent)
      // 显示弹框
      this.visible = true
      // 一级业务
      this.parent = parent
      // 本业务
      this.result = result
      // 初始化extra
      this.subCode = `二级业务索引：${this.parent.code}_${this.result.code}`

      // 再初始化form表单数据，不然业务报错
      this.$nextTick(() => {
        this.form.setFieldsValue({
          pName: this.parent.name,
          name: this.result.name,
          code: this.result.code,
          maxLifeDay: this.result.max_life_day,
          description: this.result.description
        })
      })
    },

    /**
     * 关闭
     */
    handleCancel () {
      this.visible = false
    },

    /**
     * 提交
     */
    handleSubmit () {
      const {
        form: { validateFields }
      } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        console.log('errors:', errors, 'val:', values)
        if (!errors) {
          // 检测数据是否存在
          this.verify(this.parent.id, values.name, values.code).then((res) => {
            console.log(res)
            if (res.id && res.id !== this.result.id) {
              this.$notification['error']({
                message: '提示',
                description: `已经存在相同的业务索引${res.code}`
              })
              this.confirmLoading = false
            } else {
              this.update(values).then((response) => {
                console.log('response', response)
                this.visible = false
                this.confirmLoading = false
                this.$notification['success']({
                  message: '提示',
                  description: '数据修改成功！'
                })
                // 延迟发送事件，解决列表刷新还是老数据的问题
                setTimeout(() => {
                  this.$emit('ok', values)
                }, 1500)
              })
            }
          })
        } else {
          this.confirmLoading = false
        }
      })
    },

    /**
     * 编辑数据
     */
    update (values) {
      console.log(values)
      values.description = values.description || ''
      var params = {
        sql: `update t_category_sub set name='${values.name}',modify_by='${this.userInfo.login}',code='${values.code}',description='${values.description}',max_life_day=${values.maxLifeDay}  where id=${this.result.id}`
      }
      return new Promise((resolve, reject) => {
        sqlUpdate(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            reject(error)
          }
        )
      })
    },

    /**
     * 检测是否重复
     */
    verify (parentId, name, code) {
      const params = {
        sql: `select * from t_category_sub where pid=${parentId} and name='${name}' and code='${code}'`
      }
      return new Promise((resolve, reject) => {
        sqlFindOne(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            console.log(error)
            resolve(error)
          }
        )
      })
    },

    handleInputChange (filed) {
      console.log(filed.target.value)
      this.subCode = `二级业务索引：${this.parent.code}_` + filed.target.value
    }
  }
}
</script>

<style lang="less" scoped>
</style>
